//
//  LSAppTools.m
//  Cars
//
//  Created by dllo on 15/11/19.
//  Copyright © 2015年 芦珊. All rights reserved.
//

#import "LSAppTools.h"
#import "AFNetworking.h"


@implementation LSAppTools


//我把AFN单独封装到了一个类里,并写在了一个+号方法里,以便调用
//AFN请求数据
+(void)getDataWithURL:(NSString *)url blcok:(AppToolsBlock)blcok{
    

    
    //如果网址中有中文需要使用 : 中文编码
    NSString *urlEncode = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:urlEncode parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        blcok(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];

}

+(void)getWithUrlString: (NSString *)urlString
                   body: (NSDictionary *)body
                  block: (AppToolsBlock)block{
    
    NSString *str = urlString;
    //body体
    //    @"cacheKey=Recipe.getFindRecipe&sign=&uid=&uuid=02288be08f4b871a69565746255b0de9"
    
    NSDictionary *para = body;
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPRequestOperationManager *netManager = [AFHTTPRequestOperationManager manager];
    netManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    [netManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [netManager.requestSerializer setValue:@"Mozilla/5.0 (Linux; Android 5.1; m1 note Build/LMY47D) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.114 Mobile Safari/537.36 (xiangqu; Client/Android5.1 V/2008|2.0.08 channel/meizu)[{\"channel\":\"meizu\",\"deviceInfo\":\"m1 note\",\"platform\":\"ANDROID\",\"version\":\"2008\"}] Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];
    
    [netManager POST:str parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //        NSLog(@"请求成功%@", responseObject);
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [str hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        block(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [str hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        block(result);
        NSLog(@"错误信息%@", error);
    }];
    
}

+ (void)postUrl:(NSString *)url
           body:(id)body
         result:(LHResult)result
   requestStyle:(LHRequestStyle)requestStyle
     headerFile:(NSDictionary *)headerFile
        success:(void (^)(id result))success
        failure:(void (^)(NSError *error))failure
{
    // 1.获取网络请求管理类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 2.网络请求请求体Body的类型
    switch (requestStyle) {
        case LHRequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case LHRequestString:
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError *__autoreleasing *error) {
                return parameters;
            }];
            break;
            
        default:
            break;
    }
    
    // 3.为网络请求加请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    // 4.网络请求返回值的数据类型
    switch (result) {
        case LHData:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case LHJSON:
            break;
        case LHXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    
    // 5.设置网络请求返回值支持的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain",@"application/x-javascript", nil]];
    
    // 6.发送网络请求
    [manager POST:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            success(responseObject);
            
            
            NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
            
            // 存储的沙盒路径
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            // 归档
            [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (error) {
            failure(error);
            
            // 缓存的文件夹
            NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
            success(result);
            
            
        }
    }];
    
}




@end
